<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <!--      <el-form-item label="平台参数配置标题" prop="noticeTitle">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.noticeTitle"-->
      <!--          placeholder="请输入平台参数配置标题"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="字段名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入字段名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段分组" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="字段分组" clearable>
          <el-option
            v-for="dict in dict.type.field_minutes"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('search')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('reset')}}</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">{{$t('add')}}
        </el-button>
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="tableRadio == null"
                   @click="handleUpdate">{{$t('edit')}}
        </el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="tableRadio == null"
                   @click="handleDelete">{{$t('delete')}}
        </el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="platformConfigList">
      <el-table-column width="30px">
        <template slot-scope="scope">
          <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" prop="id"/>
      <el-table-column label="字段名称" align="center" prop="title" width="200"/>
      <el-table-column label="字段Key" align="center" prop="key" width="300"/>
      <el-table-column label="字段分组" align="center" prop="groupId" width="150">
        <template slot-scope="scope">
          <DictTag :options="dict.type.field_minutes" :value="scope.row.groupId"/>
        </template>
      </el-table-column>

<!--      <el-table-column label="字段类型" align="center" prop="type" width="120">
        <template slot-scope="scope">
          {{scope.row.groupName}}
       <DictTag :options="dict.type.field_type" :value="scope.row.type"/>
                  <span v-if="scope.row.type == '2'"> - {{ scope.row.dictName }}</span>&ndash;&gt;
        </template>
      </el-table-column>-->
      <el-table-column label="必填" align="center" prop="required">
        <template slot-scope="scope">
          <DictTag :options="dict.type.boolean_value" :value="scope.row.required"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('sort')" align="center" prop="sort"/>
      <el-table-column label="多选" align="center" prop="multiple">
        <template slot-scope="scope">
          <DictTag :options="dict.type.boolean_value" :value="scope.row.multiple"/>
        </template>
      </el-table-column>
      <el-table-column label="参数值" align="center" prop="value"
                       :show-overflow-tooltip="true"  width="260"
      >
        <template slot-scope="scope">
          <!--          图片-->
          <ImagePreview v-if=" scope.row.type == 3 && scope.row.value" :src="scope.row.value" :width="50" :height="50"/>
          <!--          视频-->
          <el-button
            v-else-if="scope.row.type == 5 && scope.row.value"
            size="mini"
            type="text"
          ><a target="_blank" v-bind:href="$yun.getPreviewUrl(scope.row.value)">预览</a>
          </el-button>
          <span v-else-if="scope.row.type == 2 && dictsReady == true">{{ renderDicts(scope.row) }}</span>
          <span v-else-if="scope.row.type == 4">
            <el-button  size="mini" type="text" @click="$modal.showRichText('参数值',scope.row.richText)">预览</el-button>
          </span>
          <span v-else>{{ scope.row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="260"/>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改平台参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-row>
          <el-col :span="12">

            <el-form-item :span="12" label="字段名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入字段名称"/>
            </el-form-item>


          </el-col>

          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="字段Key" prop="key">-->
          <!--              <el-input v-model="form.key" placeholder="请输入字段Key"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="字段分组" prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择字段分组">
                <el-option v-for="dict in dict.type.field_minutes" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="字段类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择字段类型">
                <el-option v-for="dict in dict.type.field_type" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item :span="12" label="key">
              <el-input v-model="form.key" placeholder="请输入key"/>
            </el-form-item>
            <el-form-item :span="12" label="value">
              <el-input v-model="form.value" placeholder="请输入value"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="是否必填">
              <el-radio-group v-model="form.required">
                <el-radio v-for="dict in dict.type.boolean_value" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <template v-if="form.type== 2">
            <el-col :span="24">
              <el-form-item label="字典类型" prop="dictType">
                <el-select v-model="form.dictType" placeholder="请选择字典类型">
                  <el-option v-for="dict in dictData" :key="dict.dictCode"
                             :label="dict.dictType + `(${dict.dictLabel })`"
                             :value="dict.dictType"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="是否多选">
                <el-radio-group v-model="form.multiple">
                  <el-radio v-for="dict in dict.type.boolean_value" :key="dict.value" :label="dict.value">{{
                      dict.label
                    }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="24">
            <el-form-item :span="12" :label="$t('sort')" prop="sort">
              <el-input-number v-model="form.sort" :placeholder="$t('please-input',[$t('sort')])"/>
            </el-form-item>
          </el-col>

          <el-col :span="13">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位"/>
            </el-form-item>
          </el-col>


          <!--          <el-col v-if="form.type == 4">-->
          <!--            <el-form-item  label="字段值" prop="value">-->
          <!--              <editor v-model="form.value" placeholder="请输入字段值" :min-height="188"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col v-else="form.type == 0" :span="21">-->
          <!--            <el-form-item :span="12" label="字段值" prop="value">-->
          <!--              <el-input v-model="form.value" placeholder="请输入字段值"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->


          <el-col :span="13">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :height="96" v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('ok')}}</el-button>
        <el-button @click="cancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPlatformConfig,
  delPlatformConfig,
  listPlatformConfig,
  updatePlatformConfig
} from "@/api/setting/ platformConfig";
import DictTag from "@/components/DictTag/index.vue";
import {listData} from "@/api/system/dict/data";

export default {
  name: "PlatformConfig",
  components: {DictTag},
  dicts: ['field_minutes', 'field_type', 'boolean_value'],
  data() {
    return {
      //字典数据
      dictData: [],
      // 遮罩层
      loading: true,
      // 选中数组
      tableRadio: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台参数配置表格数据
      platformConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title:null,
        groupId:null,
      },
      // 表单参数
      form: {
        multiple: "0"
      },
      // 表单校验
      rules: {
        title: [
          {required: true, message: "字段名称不能为空", trigger: "blur"}
        ],
        key: [
          {required: true, message: "字段Key不能为空", trigger: "blur"}
        ],
        groupId: [
          {required: true, message: "字段分组不能为空", trigger: "change"}
        ],
        type: [
          {required: true, message: "字段类型不能为空", trigger: "change"}
        ],
        dictType: [
          {required: true, message: "字典类型不能为空", trigger: "change"}
        ]
      },
      dictsReady: false,
      dicts: {}
    };
  },
  created() {
    this.getList();

    listData().then(response => {
      this.dictData = response.rows
    });
  },
  methods: {
    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.single = selection.length != 1
    //   this.multiple = !selection.length
    // },
    /** 查询平台参数配置列表 */
    getList() {
      this.loading = true;
      this.tableRadio = null
      listPlatformConfig(this.queryParams).then(response => {

        this.platformConfigList = response.data.records || [];
        this.total = response.data.total || 0;
        this.getDictDatas(this.platformConfigList);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        key: null,
        groupId: null,
        type: null,
        multiple: "0",
        required: "0",
        remark: null,
        sort: null,
        dictType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台参数配置";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();

      this.form = {
        ...this.tableRadio,
        groupId: String(this.tableRadio.groupId)
      };

      if (this.form.multiple == null || this.form.multiple == '') {
        this.form.multiple = '0'
      }

      if (this.form.required == null || this.form.required == '') {
        this.form.required = '0'
      }


      this.open = true;
      this.title = "修改平台参数配置";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePlatformConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const result = this.dict.type.field_minutes.find(obj => obj.value === this.form.groupId);
            const result1 = this.dict.type.field_type.find(obj => obj.value === this.form.type);
            this.form.groupName = result.raw.dictValue;
            this.form.type = result1.raw.dictValue;
            addPlatformConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const ids = row.id || this.ids
      // console.log(ids)
      this.$modal.confirm(this.$t('delete-or-not')).then(() => {
        return delPlatformConfig(this.tableRadio.id);
      }).then(() => {
        this.getList();
         this.$modal.msgSuccess(this.$t('delete-success'));
      }).catch(() => {
      });
    },
    renderDicts({dictType, value}) {
      if (this.dictsReady && value && value.length > 0) {
        value = value.split(',')
        if (this.dicts[dictType]) {
          let dict = [...this.dicts[dictType]]
          if (dict && dict.length) {
            let o = {}
            dict.forEach(i => {
              o[i.dictValue] = i.dictLabel;
            })
            return value.map(v => o[v]).join(",")
          }
        }
      }
    },
    async getDictDatas(data) {
      if (data && data.length > 0) {
        let dicts = [];
        for (const i of data) {
          if (!!i.dictType && !dicts.includes(i.dictType)) {
            dicts.push(i.dictType)
            this.dicts[i.dictType] = (await this.getDicts(i.dictType)).data
          }
        }
        this.dictsReady = true
      }
    }
  }
};
</script>
